/**
 * http配置
 */

import { useUserStoreHook } from "@/store/modules/user";
import { isBoolean } from "@/utils";
import axios, {
  AxiosResponse,
  InternalAxiosRequestConfig,
  ResponseType,
} from "axios";
// import store from '../vuex/modules/login'
import { ElMessage, ElMessageBox } from "element-plus";

// axios.defaults.headers.common['Authorization'] = AUTH_TOKEN;
// build http header
function buildHeader(): { [key: string]: string } {
  return {
    "Content-Type": "application/json;charset=UTF-8",
  };
}

export const ax = axios.create({
  baseURL: host(),
  responseType: "json",
  timeout: 50000,
  withCredentials: false,
  headers: buildHeader(),
  transformRequest: [
    function (data) {
      if (data instanceof FormData) return data;
      return JSON.stringify(data);
    },
  ],
  // transformResponse: [
  //     function (data) {

  //         return data

  //     }
  // ],
  // `onUploadProgress`允许处理上传的进度事件
  onUploadProgress: function (progressEvent) {
    // 使用本地 progress 事件做任何你想要做的
  },
  // `onDownloadProgress`允许处理下载的进度事件
  onDownloadProgress: function (progressEvent) {
    // Do whatever you want with the native progress event
  },
});

//ax.defaults.baseURL='http://192.168.1.107:777/csp/';
//ax.defaults.baseURL = "http://192.168.1.205:5000/csp/"
export function host() {
  return import.meta.env.VITE_APP_BASE_API;
}

// http request 拦截器
// 请求拦截器
ax.interceptors.request.use(
  (config: InternalAxiosRequestConfig) => {
    const userStore = useUserStoreHook();
    if (userStore.token) {
      config.headers.Authorization = userStore.token;
    }
    return config;
  },
  (error: any) => {
    return Promise.reject(error);
  }
);

// http response 拦截器
ax.interceptors.response.use(
  (response: AxiosResponse) => {
    if (isBoolean(response.data.success) && !response.data.success) {
      console.log(response.data);

      ElMessageBox.alert(response.data.msg, "提示", {
        confirmButtonText: "确定",
      });
      return Promise.reject(response.data.msg);
    } else {
      return response.data instanceof ArrayBuffer ? response : response.data;
    }
  },
  (error) => {
    const { data } = error.response;
    console.log("服务器返回错误", error.response.data);
    // 状态码
    switch (error.response.status) {
      case 400:
        ElMessage({ type: "error", message: data.msg || "客户端参数发生错误" });
        break;
      case 401:
        ElMessage({ type: "error", message: "未登录" });
        break;
      case 404:
        ElMessage({ type: "error", message: data.msg || "资源不存在" });
        break;
      case 403:
        ElMessage.error({ message: data.msg || "禁止访问" });
        break;
      case 504:
      case 505:
      case 500:
        ElMessage({ type: "error", message: data.msg || "服务器发生错误" });
        break;
      default:
        ElMessage.error({ message: "未知错误!" });
    }
    // console.error(error)
    // MessageBox.alert('网络开小差了，请稍后再试', '提示', {
    //     confirmButtonText: '确定'
    // })
    return Promise.reject(error?.response?.data.msg);
  }
);

/* 手动取消请求的不显示报错 */
function handleError(err: any) {
  // 如果是手动取消的请求，不显示错误信息
  console.log("handleError1", err);
  if (axios.isCancel(err)) {
    // console.log(err)
  } else {
    // bootbox.alert(err)
  }
}

/* GET  */
export function Get<T, R>(url: string, data?: T): Promise<R> {
  // `params`是要与请求一起发送的URL参数
  // 必须是纯对象或URLSearchParams对象
  return ax
    .get(url, {
      params: data,
    })
    .then((res) => {
      return res.data;
    })
    .catch((err) => {
      handleError(err);
      throw err;
    });
}

// //下载excel
export function Download(
  url: string,
  params: any,
  responseType: ResponseType = "arraybuffer"
): Promise<any> {
  return ax({
    url: url,
    method: "get",
    params: params,
    responseType: responseType,
  });
}

/* POST */
export function Post<T, R>(url: string, data: T): Promise<R> {
  return ax
    .post(url, data)
    .then((res) => {
      console.log("响应结果", res);

      return res?.data;
    })
    .catch((err) => {
      handleError(err);
      throw err;
    });
}
/* PUT */
export function Put<T>(url: string, data: T): Promise<any> {
  return ax
    .put(url, data)
    .then((res) => {
      return res.data || res;
    })
    .catch((err) => {
      handleError(err);
      throw err;
    });
}
/* PATCH */
export function Patch<T, R>(url: string, data: T): Promise<R> {
  return ax
    .patch(url, data)
    .then((res) => {
      return res.data;
    })
    .catch((err) => {
      handleError(err);
      throw err;
    });
}
/* DELETE */
export function Delete<T extends {}, R>(url: string, data?: T): Promise<R> {
  return ax
    .delete(url, { data: data })
    .then((res) => {
      return res.data;
    })
    .catch((err) => {
      handleError(err);
      throw err;
    });
}
